#pragma once
#include<vector>

namespace sxn
{
    template <class T, class Container = vector<T>, class Compare = less<T> >
    class priority_queue
    {
    public:
        priority_queue(){}

        void AdjustDown(Container& a, int n, int root)
        {
            int parent = root;
            int child = parent * 2 + 1;
            while (child < n) 
            {
                if (child + 1 < n && _comp(a[child] , a[child+1]))
                {
                    ++child;
                }
                if (_comp(a[parent] , a[child]))
                {
                    swap(a[child], a[parent]);
                    parent = child;
                    child = parent * 2 + 1;
                }
                else
                {
                    break;
                }
            }
        }

        void AdjustUp(int child)
        {
            Compare com;
            int parent = (child - 1) / 2;
            while (child > 0)
            {
                //if (_con[parent] < _con[child])
                if (com(_c[parent], _c[child]))
                {
                    swap(_c[child], _c[parent]);
                    child = parent;
                    parent = (child - 1) / 2;
                }
                else
                {
                    break;
                }
            }
        }

        template <class InputIterator>
        priority_queue(InputIterator first, InputIterator last)
            :_c(first, last)
        {
            int size = _c.size();
            int i = (size - 2) / 2;
            while (i >= 0)
            {
                AdjustDown(_c, last - first, i);
                i--;
            }
        }
        bool empty() const
        {
            return _c.empty();
        }
        size_t size() const
        {
            return _c.size();
        }
        T& top() 
        {
            return _c[0];
        }
        const T& top()const
        {
            return _c[0];
        }
        void push(const T& x)
        {
            _c.push_back(x);
            AdjustUp(_c.size() - 1);
        }
        void pop()
        {
            swap(_c[0], _c[_c.size() - 1]);
            _c.pop_back();
            AdjustDown(_c, _c.size(), 0);
        }
    private:
        Container _c;
        Compare _comp;
    };
};


